package com.rickpan.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import jakarta.persistence.*;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 工作统计实体类
 * 用于存储工作记录的统计数据
 */
@Entity
@Table(name = "work_statistics")
@EntityListeners(AuditingEntityListener.class)
public class WorkStatistics {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "user_id", nullable = false)
    private Long userId;

    @Column(name = "stat_date", nullable = false)
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate statDate;

    @Enumerated(EnumType.STRING)
    @Column(name = "stat_type", nullable = false)
    private StatType statType;

    // 工作记录统计
    @Column(name = "total_records")
    private Integer totalRecords = 0;

    @Column(name = "completed_records")
    private Integer completedRecords = 0;

    @Column(name = "in_progress_records")
    private Integer inProgressRecords = 0;

    @Column(name = "pending_records")
    private Integer pendingRecords = 0;

    @Column(name = "cancelled_records")
    private Integer cancelledRecords = 0;

    // 时间统计
    @Column(name = "total_time_spent")
    private Integer totalTimeSpent = 0; // 分钟

    @Column(name = "avg_time_spent", precision = 10, scale = 2)
    private BigDecimal avgTimeSpent = BigDecimal.ZERO;

    @Column(name = "max_time_spent")
    private Integer maxTimeSpent = 0;

    @Column(name = "min_time_spent")
    private Integer minTimeSpent = 0;

    // 分类和优先级统计（JSON格式）
    @Column(name = "category_stats", columnDefinition = "JSON")
    private String categoryStats;

    @Column(name = "priority_stats", columnDefinition = "JSON")
    private String priorityStats;

    // 效率指标
    @Column(name = "completion_rate", precision = 5, scale = 2)
    private BigDecimal completionRate = BigDecimal.ZERO;

    @Column(name = "efficiency_score", precision = 5, scale = 2)
    private BigDecimal efficiencyScore = BigDecimal.ZERO;

    @Column(name = "productivity_index", precision = 5, scale = 2)
    private BigDecimal productivityIndex = BigDecimal.ZERO;

    // 报告统计
    @Column(name = "daily_reports_count")
    private Integer dailyReportsCount = 0;

    @Column(name = "weekly_reports_count")
    private Integer weeklyReportsCount = 0;

    @Column(name = "monthly_reports_count")
    private Integer monthlyReportsCount = 0;

    @CreatedDate
    @Column(name = "created_at", nullable = false, updatable = false)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createdAt;

    @LastModifiedDate
    @Column(name = "updated_at", nullable = false)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updatedAt;

    // 统计类型枚举
    public enum StatType {
        DAILY("日统计"),
        WEEKLY("周统计"),
        MONTHLY("月统计");

        private final String displayName;

        StatType(String displayName) {
            this.displayName = displayName;
        }

        public String getDisplayName() {
            return displayName;
        }
    }

    // 构造函数
    public WorkStatistics() {}

    public WorkStatistics(Long userId, LocalDate statDate, StatType statType) {
        this.userId = userId;
        this.statDate = statDate;
        this.statType = statType;
    }

    // Getter和Setter方法
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public Long getUserId() { return userId; }
    public void setUserId(Long userId) { this.userId = userId; }

    public LocalDate getStatDate() { return statDate; }
    public void setStatDate(LocalDate statDate) { this.statDate = statDate; }

    public StatType getStatType() { return statType; }
    public void setStatType(StatType statType) { this.statType = statType; }

    public Integer getTotalRecords() { return totalRecords; }
    public void setTotalRecords(Integer totalRecords) { this.totalRecords = totalRecords; }

    public Integer getCompletedRecords() { return completedRecords; }
    public void setCompletedRecords(Integer completedRecords) { this.completedRecords = completedRecords; }

    public Integer getInProgressRecords() { return inProgressRecords; }
    public void setInProgressRecords(Integer inProgressRecords) { this.inProgressRecords = inProgressRecords; }

    public Integer getPendingRecords() { return pendingRecords; }
    public void setPendingRecords(Integer pendingRecords) { this.pendingRecords = pendingRecords; }

    public Integer getCancelledRecords() { return cancelledRecords; }
    public void setCancelledRecords(Integer cancelledRecords) { this.cancelledRecords = cancelledRecords; }

    public Integer getTotalTimeSpent() { return totalTimeSpent; }
    public void setTotalTimeSpent(Integer totalTimeSpent) { this.totalTimeSpent = totalTimeSpent; }

    public BigDecimal getAvgTimeSpent() { return avgTimeSpent; }
    public void setAvgTimeSpent(BigDecimal avgTimeSpent) { this.avgTimeSpent = avgTimeSpent; }

    public Integer getMaxTimeSpent() { return maxTimeSpent; }
    public void setMaxTimeSpent(Integer maxTimeSpent) { this.maxTimeSpent = maxTimeSpent; }

    public Integer getMinTimeSpent() { return minTimeSpent; }
    public void setMinTimeSpent(Integer minTimeSpent) { this.minTimeSpent = minTimeSpent; }

    public String getCategoryStats() { return categoryStats; }
    public void setCategoryStats(String categoryStats) { this.categoryStats = categoryStats; }

    public String getPriorityStats() { return priorityStats; }
    public void setPriorityStats(String priorityStats) { this.priorityStats = priorityStats; }

    public BigDecimal getCompletionRate() { return completionRate; }
    public void setCompletionRate(BigDecimal completionRate) { this.completionRate = completionRate; }

    public BigDecimal getEfficiencyScore() { return efficiencyScore; }
    public void setEfficiencyScore(BigDecimal efficiencyScore) { this.efficiencyScore = efficiencyScore; }

    public BigDecimal getProductivityIndex() { return productivityIndex; }
    public void setProductivityIndex(BigDecimal productivityIndex) { this.productivityIndex = productivityIndex; }

    public Integer getDailyReportsCount() { return dailyReportsCount; }
    public void setDailyReportsCount(Integer dailyReportsCount) { this.dailyReportsCount = dailyReportsCount; }

    public Integer getWeeklyReportsCount() { return weeklyReportsCount; }
    public void setWeeklyReportsCount(Integer weeklyReportsCount) { this.weeklyReportsCount = weeklyReportsCount; }

    public Integer getMonthlyReportsCount() { return monthlyReportsCount; }
    public void setMonthlyReportsCount(Integer monthlyReportsCount) { this.monthlyReportsCount = monthlyReportsCount; }

    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }

    public LocalDateTime getUpdatedAt() { return updatedAt; }
    public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }

    /**
     * 计算总报告数
     */
    public Integer getTotalReportsCount() {
        return (dailyReportsCount != null ? dailyReportsCount : 0) +
               (weeklyReportsCount != null ? weeklyReportsCount : 0) +
               (monthlyReportsCount != null ? monthlyReportsCount : 0);
    }

    /**
     * 计算完成率
     */
    public void calculateCompletionRate() {
        if (totalRecords != null && totalRecords > 0 && completedRecords != null) {
            this.completionRate = BigDecimal.valueOf(completedRecords)
                .divide(BigDecimal.valueOf(totalRecords), 2, BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(100));
        } else {
            this.completionRate = BigDecimal.ZERO;
        }
    }

    /**
     * 计算平均工时
     */
    public void calculateAvgTimeSpent() {
        if (totalRecords != null && totalRecords > 0 && totalTimeSpent != null) {
            this.avgTimeSpent = BigDecimal.valueOf(totalTimeSpent)
                .divide(BigDecimal.valueOf(totalRecords), 2, BigDecimal.ROUND_HALF_UP);
        } else {
            this.avgTimeSpent = BigDecimal.ZERO;
        }
    }

    /**
     * 计算效率评分（基于完成率和时间利用率）
     */
    public void calculateEfficiencyScore() {
        // 简单的效率评分算法
        BigDecimal completionWeight = BigDecimal.valueOf(0.6);
        BigDecimal timeWeight = BigDecimal.valueOf(0.4);
        
        BigDecimal timeScore = BigDecimal.valueOf(100); // 默认时间评分
        if (avgTimeSpent != null && avgTimeSpent.compareTo(BigDecimal.ZERO) > 0) {
            // 基于平均工时计算时间评分（假设理想工时为120分钟）
            BigDecimal idealTime = BigDecimal.valueOf(120);
            timeScore = idealTime.divide(avgTimeSpent.max(idealTime), 2, BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(100));
        }
        
        this.efficiencyScore = (completionRate != null ? completionRate : BigDecimal.ZERO)
            .multiply(completionWeight)
            .add(timeScore.multiply(timeWeight));
    }
}
